package cn.weixin.song.model;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import cn.weixin.song.model.base.BaseAppMenu;
import cn.weixin.song.util.WeixinUtils;

import com.github.sd4324530.fastweixin.api.entity.Menu;
import com.github.sd4324530.fastweixin.api.entity.MenuButton;
import com.github.sd4324530.fastweixin.api.enums.MenuType;
import com.github.sd4324530.fastweixin.api.enums.ResultType;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jcbase.core.model.Condition;
import com.jcbase.core.model.Operators;
import com.jcbase.core.util.CommonUtils;
import com.jfinal.kit.JsonKit;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class AppMenu extends BaseAppMenu<AppMenu> {
	public static final AppMenu dao = new AppMenu();
	
	/**
	 * 刷新菜单
	 * @author eason
	 * @param wxAppId
	 */
	public void refreshAppMenu(String wid){
		App app=App.dao.getApp(wid);
		if(app!=null){
			LinkedHashMap<String, String> orderby=Maps.newLinkedHashMap();
			orderby.put("seq", "asc");
			Set<Condition> conditions=Sets.newHashSet();
			conditions.add(new Condition("pid",Operators.EQ,null));
			conditions.add(new Condition("app_id",Operators.EQ,app.getId()));
			//获取一级菜单，最多3项
			List<AppMenu> list=this.getList(1, 3, conditions, orderby);
			Menu menu=new Menu();
	    	List<MenuButton> topButtons=new ArrayList<MenuButton>();
			for(AppMenu item : list){
				MenuButton topButton=new MenuButton();
				topButton.setKey(item.getMenuKey());
				topButton.setType(MenuType.valueOf(item.getType()));
				topButton.setName(item.getName());
				topButton.setUrl(item.getUrl());
				conditions=Sets.newHashSet();
				conditions.add(new Condition("pid",Operators.EQ,item.getId()));
				//获取二级菜单，最多5项
				List<AppMenu> sublist=this.getList(1, 5, conditions, orderby);
				if(sublist.size()>0){
					List<MenuButton> subButtons=new ArrayList<MenuButton>();
					for(AppMenu subMenu : sublist){
						MenuButton subButton=new MenuButton();
						subButton.setKey(subMenu.getMenuKey());
						subButton.setType(MenuType.valueOf(subMenu.getType()));
						subButton.setName(subMenu.getName());
						subButton.setUrl(subMenu.getUrl());
						subButtons.add(subButton);
					}
					topButton.setSubButton(subButtons);
				}
				topButtons.add(topButton);
			}
			menu.setButton(topButtons);
			//调用fastweixin API创建或刷新微信公众号菜单
			ResultType  resultType =WeixinUtils.getMenuAPI(wid).createMenu(menu);
			logger.debug("resultType:"+JsonKit.toJson(resultType));
		}
	}
	public AppMenu getByKey(String key){
		return this.get(CommonUtils.getConditions(new Condition("menu_key",Operators.EQ,key)));
	}
}
